package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.product.api.vo.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired(required = false)
    private RemoteCartService remoteCartService;
    @Autowired(required = false)
    private RemoteUserAddressService remoteUserAddressService;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    private OrderItemMapper orderItemMapper;
    @Autowired(required = false)
    private OrderLogMapper orderLogMapper;
    @Autowired(required = false)
    private RemoteSkuStockService remoteSkuStockService;
    @Autowired
    private RabbitService rabbitService;

    @Override
    public TradeVo orderTradeData() {

        R<List<CartInfo>> cartCheckedResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (cartCheckedResult.getCode() == R.FAIL) {
            throw new ServiceException(cartCheckedResult.getMsg());
        }

        List<CartInfo> cartInfoList = cartCheckedResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("未选中商品");
        }

        // 封装 List<OrderItem>
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);

            return orderItem;
        }).toList();

        // 计算商品总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(generateTradeNo(SecurityUtils.getUserId()));
        tradeVo.setIsBuy(false);

        return tradeVo;
    }

    // 提交订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {

        //获取用户 id
        Long userId = SecurityUtils.getUserId();

        // 1 防止订单重复提交&防止页面停留超时
        // 1.1 若订单号在 redis已存在，说明订单已提交，获取的订单号与当前订单号不一致，则抛出异常
        /*
        // V1版本，需要借助辅助方法才能实现
        if (!checkTradeNo(orderForm.getTradeNo())) {
            throw new ServiceException("订单重复提交");
        }
        deleteTradeNo();
        */

        // V2版本，使用 lua脚本解决原子性的问题
        String userTradeKey = "userTradeNo:" + userId;
        // 将键的值更为 processed  表示已处理
        // return 1 表示处理成功
        // return -1  键存在但值不匹配，表示重复提交
        // return 0   键不存在，订单过期
        // 构建流水号 key，注意取出流水号时前面的字符串要一致
        String scriptText = """
            -- 检查 Redis 中 KEYS[1] 对应的值是否等于 ARGV[1]
            if redis.call('get', KEYS[1]) == ARGV[1] then
                -- 如果相等，将 KEYS[1] 的值设置为 'processed'，并设置过期时间为 ARGV[2] 秒
                redis.call('set', KEYS[1], 'processed', 'ex', ARGV[2])
                -- 返回状态码 1 表示操作成功
                return 1
            else
                -- 如果不相等，检查 KEYS[1] 是否存在于 Redis 中
                if redis.call('exists', KEYS[1]) == 1 then
                    -- 如果存在，返回状态码 -1 表示键存在但值不匹配
                    return -1
                else
                    -- 如果不存在，返回状态码 0 表示键不存在
                    return 0
                end
            end
            """;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);  // 脚本字符串
        redisScript.setResultType(Long.class);  // 脚本返回值类型
        Long flag = (Long)redisTemplate.execute(
                redisScript,
                Arrays.asList(userTradeKey),  // keys列表
                orderForm.getTradeNo(), 3);  // argv列表，3是设置过期时间的
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if(flag == -1){
            throw new ServiceException("请勿重复提交订单");
        }

        // 2 判断价格是否改变并更新购物车中的商品价格
        // 2.1 批量获取商品实时价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();

        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);

        if (skuPriceListResult.getCode() == R.FAIL) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }

        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();

        // 2.2 并判断价格是否变更
        /*
        // V1版，复杂度为 O(n²)
        for (OrderItem orderItem : orderItemList) {
            for (SkuPriceVo skuPriceVo : skuPriceVoList) {
                if (!Objects.equals(orderItem.getSkuId(), skuPriceVo.getSkuId())) {
                    continue;
                }
                if (orderItem.getSkuPrice().compareTo(skuPriceVo.getSalePrice()) != 0) {
                    throw new ServiceException("商品价格有变更，请重新下单");
                }
            }
        }
        */

        // V2版，复杂度为 O(n)
        // 将列表转换成 hashMap
        Map<Long, BigDecimal> skuPriceMap = skuPriceVoList
                .stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        String priceCheckResult = "";
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuPriceMap.get(orderItem.getSkuId())) != 0) {
                priceCheckResult += orderItem.getSkuName() + "\n";
            }
        }

        // 2.3 如果有变更且不是立即购买的，则更新购物车中的商品价格
        if (StringUtils.hasText(priceCheckResult) && !orderForm.getIsBuy()) {
            R<Boolean> booleanResult = remoteCartService.updateCartPrice(SecurityConstants.INNER);
            if (booleanResult.getCode() == R.FAIL) {
                log.error(booleanResult.getMsg());
                throw new ServiceException("更新购物车商品价格失败：" + booleanResult.getMsg());
            }

            throw new ServiceException("商品价格有变更，请重新下单：\n" + priceCheckResult);
        }

        // 3 校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();

            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuName(orderItem.getSkuName());

            return skuLockVo;
        }).toList();
        R<String> stringResult = remoteSkuStockService.checkAndLock(
                orderForm.getTradeNo(),
                skuLockVoList,
                SecurityConstants.INNER
        );

        if (stringResult.getCode() == R.FAIL) {
            throw new ServiceException("远程调用失败：" + stringResult.getMsg());
        }
        String stringResultData = stringResult.getData();
        if (StringUtils.hasText(stringResultData)) {
            throw new ServiceException(stringResultData);
        }

        // 4 下单
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();

            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderForm.getTradeNo()
            );

            throw new ServiceException("下单失败");
        }

        // 5 删除购物车中选中的商品
        if (!orderForm.getIsBuy()) {
            R<Boolean> booleanResult = remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
            if (booleanResult.getCode() == R.FAIL) {
                log.error(booleanResult.getMsg());
                // 非核心流程不影响程序的运行
                throw new ServiceException(booleanResult.getMsg());
            }
        }

        return 1L;
    }

    @Override
    public TradeVo buy(Long skuId) {

        R<ProductSkuVo> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (productSkuResult.getCode() == R.FAIL) {
            throw new ServiceException("远程调用失败：" + productSkuResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuResult.getData();
        ArrayList<OrderItem> orderItemList = new ArrayList<>();

        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setThumbImg(productSkuVo.getThumbImg());
        orderItem.setSkuPrice(productSkuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(generateTradeNo(SecurityUtils.getUserId()));
        tradeVo.setIsBuy(true);

        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {

        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                .eq(OrderInfo::getUserId, SecurityUtils.getUserId())
                .orderByDesc(OrderInfo::getCreateTime);
        // 查询所有订单列表
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(orderInfoList)) {
            /*
            // V1版
            for (OrderInfo orderInfo : orderInfoList) {
                Long orderId = orderInfo.getId();
                LambdaQueryWrapper<OrderItem> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderItem::getOrderId, orderId);
                List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper1);
                orderInfo.setOrderItemList(orderItemList);
            }
            */

            // V2版，优化
            //查询所有订单项列表
            LambdaQueryWrapper<OrderItem> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(
                    OrderItem::getOrderId,
                    orderInfoList.stream().map(OrderInfo::getId).toList());
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper1);
            // 将订单项列表根据订单 id进行分组
            Map<Long, List<OrderItem>> listMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(listMap.get(orderInfo.getId()));
            }
        }

        return orderInfoList;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {

        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setOrderStatus(-1);
        orderInfo.setCancelTime(new Date());
        orderInfo.setCancelReason("七天无理由有退货");
        orderInfo.setUpdateBy(SecurityUtils.getUsername());
        baseMapper.updateById(orderInfo);

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(-1);
        orderLog.setNote("用户取消订单");
        orderLogMapper.insert(orderLog);

        // 解锁库存
        OrderInfo order = baseMapper.selectById(orderId);
        rabbitService.sendMessage(
                MqConst.EXCHANGE_PRODUCT,
                MqConst.ROUTING_UNLOCK,
                order.getOrderNo()
        );
    }

    /**
     * 保存订单相关的数据
     */
    private Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());

        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (userAddressResult.getCode() == R.FAIL) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();

        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        // 计算商品总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(orderItem ->
                    orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()))
                )
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //设置商品总价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格
        orderInfo.setTotalAmount(totalAmount);

        //订单状态
        orderInfo.setOrderStatus(0);//待付款
        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);
        baseMapper.insert(orderInfo);

        // 保存订单项记录：orderItem
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }

        // 保存订单日志记录：orderLog
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

    /**
     * 生成订单号并保存到 redis
     */
    private String generateTradeNo(Long userId) {

        // 构建流水号 key，注意取出流水号时前面的字符串要一致
        String userTradeKey = "userTradeNo:" + userId;
        // 流水号 value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        // 将流水号放入到 redis中，5分钟过期
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);

        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(String tradeNo) {

        String userTradeKey = "userTradeNo:" + SecurityUtils.getUserId();
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);

        return tradeNo.equals(redisTradeNo);
    }

    /**
     * 删除流水号
     */
    private void deleteTradeNo() {

        String userTradeKey = "userTradeNo:" + SecurityUtils.getUserId();
        redisTemplate.delete(userTradeKey);
    }
}
